﻿using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Configuration;
using System.Web;
using System.Text;
using System.Web.UI;

namespace BTS.COMMON
{
    public class BTSTools
    {
        /// <summary>
        /// 后台输出js弹出代码
        /// </summary>
        /// <param name="message"></param>
        /// <param name="toURL"></param>
        /// <param name="page"></param>
        public static void AlertUrl(string message, string url, Page page)
        {
            #region
            string js = "<script language='javascript'>alert('{0}');window.location.href='{1}'</script>";
            if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "AlertAndRedirect"))
            {
                page.ClientScript.RegisterStartupScript(page.GetType(), "AlertAndRedirect", string.Format(js, message, url));
            }
            #endregion
        }

        /// <summary>
        /// 后台输出js弹出代码
        /// </summary>
        /// <param name="message"></param>
        public static void Alert(string message, Page page)
        {
            string js = "<script language='javascript'>alert('{0}');</script>";
            if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), "MESSAGE"))
            {
                page.ClientScript.RegisterStartupScript(page.GetType(), "MESSAGE", string.Format(js, message));
            }
        }

        /// <summary>
        /// 后台执行前台脚本
        /// </summary>
        /// <param name="func"></param>
        /// <param name="page"></param>
        public static void DoJSFunc(string func, Page page)
        {
            ClientScriptManager cs = page.ClientScript;
            cs.RegisterStartupScript(page.GetType(), "", "<script type=\"text/javascript\">" + func + "</script>");
        }

        /// <summary>
        /// YYYYMMDD转换成YYYY-MM-DD
        /// </summary>
        /// <param name="strDateInput"></param>
        /// <returns></returns>
        public static string GetDateTXT(string strDateInput)
        {
            string strDate = "";

            if (strDateInput.Length != 8)
                return strDate;

            strDate = strDateInput;

            strDate = strDate.Insert(4, "-");
            strDate = strDate.Insert(7, "-");

            return strDate;
        }

        /// <summary>
        /// HHmmss转换为HH:mm:ss
        /// </summary>
        /// <param name="strTimeInput"></param>
        /// <returns></returns>
        public static string GetTimeTXT(string strTimeInput)
        {
            string strTime = "";

            if (strTimeInput.Length != 6)
                return strTime;

            strTime = strTimeInput;

            strTime = strTime.Insert(2, ":");
            strTime = strTime.Insert(5, ":");

            return strTime;
        }

        /// <summary>
        /// YYYYMMDDHHmmss转换成YYYY-MM-DD HH:mm:ss
        /// </summary>
        /// <param name="strDateInput"></param>
        /// <param name="strTimeInput"></param>
        /// <returns></returns>
        public static string GetDateTimeTXT(string strDateInput, string strTimeInput)
        {
            string strDateTime = "";
            strDateTime = GetDateTXT(strDateInput) + " " + GetTimeTXT(strTimeInput);
            return strDateTime;
        }

        /// <summary>
        /// 把\str\\str\\str\...转换成英文逗号分隔
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static string GetMultiValueTXT(string strValue)
        {
            string strReturnValue = strValue;

            strReturnValue = strReturnValue.Replace("\\\\", ",");
            strReturnValue = strReturnValue.Replace("\\", "");

            return strReturnValue;
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        public static string DecodePassword(string strInput)
        {
            string strOutput = "";
            try
            {
                if (string.IsNullOrEmpty(strInput))
                    return strOutput;

                string strAscii = "", strBuffer = "";

                int nLength = strInput.Length;

                int nRand;
                strBuffer = strInput.Substring(0, 1);
                nRand = Convert.ToInt16(strBuffer);
                nRand += 6;

                int nValue, nIncrease = nRand;

                for (int i = 1; i < nLength; i++)
                {
                    strBuffer = strInput.Substring(i, 1);
                    nValue = Int32.Parse(strBuffer, System.Globalization.NumberStyles.HexNumber);
                    nValue -= nIncrease;
                    nIncrease--;

                    if (nIncrease == 1)
                        nIncrease = nRand;

                    if (nValue < 0)
                        nValue += 16;

                    strBuffer = String.Format("{0:X}", nValue);
                    strAscii += strBuffer;
                }

                nLength = strAscii.Length;
                for (int i = 0; i < nLength; i += 2)
                {
                    strBuffer = strAscii.Substring(i, 2);
                    int nHexValue = Convert.ToInt32(strBuffer, 16);
                    strBuffer = Char.ConvertFromUtf32(nHexValue);
                    strOutput += strBuffer;
                }

            }
            catch (Exception ex)
            {

                return "";

            }

            return strOutput;
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        public static string EncodePassword(string strInput)
        {
            string strOutput = "";

            string strAscii = "", strBuffer = "";

            char[] cValues = strInput.ToCharArray();
            foreach (char ch in cValues)
            {
                int nCharValue = Convert.ToInt32(ch);
                strBuffer = String.Format("{0:X2}", nCharValue);
                strAscii += strBuffer;
            }

            Random rand = new Random();
            int nRand = rand.Next(9);
            strOutput = String.Format("{0:D}", nRand);

            nRand += 6;

            int nValue, nIncrease = nRand;

            int nLength = strAscii.Length;
            for (int i = 0; i < nLength; i++)
            {
                strBuffer = strAscii.Substring(i, 1);
                nValue = Int32.Parse(strBuffer, System.Globalization.NumberStyles.HexNumber);
                nValue += nIncrease;
                nIncrease--;
                if (nIncrease == 1)
                    nIncrease = nRand;
                if (nValue > 15)
                    nValue -= 16;
                strBuffer = String.Format("{0:X}", nValue);
                strOutput += strBuffer;
            }

            return strOutput;
        }

        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            string ip = string.Empty;
            if (null != HttpContext.Current.Request)
            {
                ip = HttpContext.Current.Request.UserHostAddress;

                if (HttpContext.Current.Request.ServerVariables != null)
                {
                    ArrayList list = new ArrayList();
                    foreach (string i in HttpContext.Current.Request.ServerVariables.AllKeys)
                    {
                        list.Add(i);
                    }
                    if (list.Contains("REMOTE_ADDR"))
                        ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                if (ip == null) ip = string.Empty;
            }
            return ip;
        }

        /// <summary>
        /// 位运算 和
        /// </summary>
        /// <param name="nPrivilege"></param>
        /// <param name="nDoctorPrivilege"></param>
        /// <returns></returns>
        public static bool ValidatePrivilege(int nPrivilege, int nDoctorPrivilege)
        {
            if ((nPrivilege & nDoctorPrivilege) != 0)
                return true;

            return false;
        }

        /// <summary>
        /// XSLT模板成型
        /// </summary>
        /// <param name="xmlData"></param>
        /// <param name="xslt"></param>
        /// <returns></returns>
        public static string GetXSLT(string xmlData, string xslt)
        {
            StringWriter output = new StringWriter();
            try
            {
                XmlReader reader;
                reader = XmlReader.Create(new StringReader(xmlData));
                //装入xsl对象  
                XslCompiledTransform xsldoc = new XslCompiledTransform();
                xsldoc.Load(xslt);
                //把xml转化成html页面  
                xsldoc.Transform(reader, null, output);
            }
            catch (Exception ex)
            {
                BTSLog.DoLog("BTS.COMMON.BTSTools.cs 方法：GetXSLT异常", ex.Message, ex.StackTrace);
                return "";
            }
            return output.ToString();
        }


        /// <summary>
        /// 读取cookie值
        /// </summary>
        /// <param name="strName"></param>
        /// <returns></returns>
        public static string GetCookie(string strName)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie != null)
            {
                return HttpUtility.UrlDecode(cookie.Value.ToString(), System.Text.Encoding.GetEncoding("gb2312"));
            }
            return "";
        }
        /// <summary>
        /// 写入cookie值
        /// </summary>
        /// <param name="strName"></param>
        /// <param name="strValue"></param>
        public static void SetCookie(string strName, string strValue)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = HttpUtility.UrlEncode(strValue, System.Text.Encoding.GetEncoding("gb2312"));
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 表格数据转换为json格式
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private static string DataTableToJson(System.Data.DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i != 0) { jsonBuilder.Append(","); }
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\'");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\':\'");
                    jsonBuilder.Append(dt.Rows[i][j].ToString().Replace("\"", "").Replace("\'", ""));
                    jsonBuilder.Append("\',");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("}");
            }
            jsonBuilder.Append("]");
            return jsonBuilder.ToString();
        }
    }
}
